package cn.charmaine.basic.base.controller;

import cn.charmaine.basic.util.AjaxResult;
import cn.charmaine.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
/**
 * 上传（post）和删除
 */
public class DfsController {
    /**
     * 上传
     * @return
     */
    @PostMapping
    public AjaxResult uploadFile(@RequestPart(value = "file",required = true) MultipartFile file){
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件扩展名（后缀去除.）
            String extName = filename.substring(filename.lastIndexOf(".")+1);
            String path = FastdfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.thisSuccess().setResultObj(path);//成功返回信息+路径
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.thisSuccess().setSuccess(false).setMessage("服务器繁忙,请稍后重试!");
        }
    }

    //localhost:8080/xxx?id=1    http://123.207.27.208/group1/M00/00/6B/CgAIC2LEKxSAJfXxAAUw8khqWzM581.jpg
    @DeleteMapping
    public AjaxResult deleteFile(@RequestParam(value = "path",required = true) String path){
        // path= /group1/M00/00/6B/CgAIC2LEKxSAJfXxAAUw8khqWzM581.jpg
        String pathTmp = path.substring(1);// group1/M00/00/6B/CgAIC2LEKxSAJfXxAAUw8khqWzM581.jpg
        String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));// group1
        String remotePath = pathTmp.substring((pathTmp.indexOf("/") + 1));// M00/00/6B/CgAIC2LEKxSAJfXxAAUw8khqWzM581.jpg
        boolean flag = FastdfsUtil.delete(groupName, remotePath);
        if(flag){
            return AjaxResult.thisSuccess();
        }else {
            return AjaxResult.thisSuccess().setSuccess(false).setMessage("服务器繁忙,请稍后重试!");
        }
    }
}
